import 'dart:async';

import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/pages/mall_app/account_safe_modify_phone.dart/state.dart';
import 'package:yp/router.dart';
import 'package:yp/services/api.dart';

import '../../../helper.dart';

class VerifyPhoneLogic extends GetxController {
  final VerifyPhoneState state = VerifyPhoneState();
  @override
  void onInit() {
    super.onInit();
    var _mobile = SpUtil.getString('number');
    if (_mobile.length > 4) {
      var sufixLength = (_mobile.length - 4) ~/ 2;
      var prefixLength = _mobile.length - 4 - sufixLength;
      state.photo = _mobile.substring(0, prefixLength) +
          '****' +
          _mobile.substring(_mobile.length - sufixLength, _mobile.length);
    } else {
      state.photo = _mobile;
    }
  }

  //请求发送验证码
  void sendSms() {
    if (!state.verifyEnable) {
      return;
    }
    state.verifyEnable = false;
    var params = {
      "mobile": SpUtil.getString('number'),
      "verify_code_type": "memBindCode"
    };
    Api.sendSms(params).listen((event) {
      if (event['code'] == 0) {
        toast("验证码已发送,请注意查收");
        state.smsData = event;
      } else {
        toast(event['message']);
        state.verifyEnable = true;
      }
      state.focusNode.canRequestFocus = true;
      update();
    });

    state.timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (state.seconds == 0) {
        state.timer?.cancel();
        state.verifyText = '重新发送';
        state.seconds = 5;
        state.verifyEnable = true;
        state.focusNode.canRequestFocus = true;
        update();
        return;
      }
      state.verifyEnable = false;
      state.seconds = --state.seconds;
      state.verifyText = "已发送${state.seconds}s";
      print("已发送${state.seconds}s");
      update();
    });
  }

  netStep() {
    if (state.textCtrl.text == null) {
      toast('请输入验证码');
      return;
    }
    if (state.smsData == null) {
      toast('请先获取验证码');
      return;
    }
    state.verifyEnable = false;
    var params = {
      "tenant_num_id": 1,
      "data_sign": "1",
      "sms_verify_type": 'memBindCode',
      "sms_verify_code": state.textCtrl.text,
      "sms_verify_token": state.smsData['token'],
      "mobile": SpUtil.getString('number'),
    };
    Api.modfiyOldPhone(params).listen((event) {
      if (event['code'] == 0) {
        Get.toNamed(RouteConfig.modifyPhone, arguments: {
          'token': state.smsData['token'],
          'code': state.textCtrl.text
        });
      } else {
        toast(event['message']);
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    state.timer.cancel();
  }
}
